<?php

/**
 * WeEngine System
 *
 * (c) We7Team 2021 <https://www.w7.cc>
 *
 * This is not a free software
 * Using it under the license terms
 * visited https://www.w7.cc for more details
 */

namespace App\Http\Controllers;

use App\Exceptions\LogicErrorException;
use App\Http\Logic\PayLogic;
use App\Http\Validator\PayRPCValidate;
use Illuminate\Http\Request;
use Itwmw\Validate\Attributes\Validator;

class WechatController
{
    public function pc()
    {
        $data = [
            'pay_type'     => 'wechat',
            'method'       => 'payTransactionsNative',
            'description'  => '测试支付',
            'out_trade_no' => md5(time() . rand(1000, 9999)),
            'total'        => 1,
            'notify_uri'   => MODULE_URI . '/api/pay/notify',
        ];

        return PayLogic::create($data);
    }

    #[Validator(validate: PayRPCValidate::class, fields: ['out_trade_no'])]
    public function refund(Request $request)
    {
        $data = get_validate_data($request);

        $out_trade_no = $data->get('out_trade_no');

        $log = PayLogic::refund('wechat', $out_trade_no);

        $params = [
            'pay_type'      => 'wechat',
            'method'        => 'refund',
            'out_refund_no' => md5(time() . rand(1000, 9999)),
            'out_trade_no'  => $out_trade_no,
            'refund'        => $log->amount * 100,
            'total'         => $log->amount * 100
        ];

        $result = json_decode(PayLogic::rpc($params)->getContents(), true);

        if (($result['code'] ?? 0) == 0) {
            $log->status = 2;
            $log->save();
            return json_success('退款成功');
        }

        throw new LogicErrorException($result['message'] ?? '退款请求失败');
    }
}
